import Epub, { type Book } from 'epubjs'
import { type MessageApi } from 'naive-ui'

let message: MessageApi;
const parser = new DOMParser()
const baseHref = window.location.href
interface ISpineItem {
  canonical: string
}

function extractImageUrlsFromHTML(htmlContent: string) {
  const doc = parser.parseFromString(htmlContent, 'text/html')
  // console.log("🚀 ~ extractImageUrlsFromHTML ~ doc:", doc)
  // 查找所有图片
  const imgElement = doc.querySelector('img') as HTMLImageElement
  if (!imgElement) {
    message.error('抱歉，无法解析当前书籍')
    throw new Error('无法解析')
  }
  const src = imgElement.getAttribute('src') || ''
  // 解析相对路径为绝对路径
  const absolutePath = new URL(src, baseHref).pathname
  console.log("🚀 ~ extractImageUrlsFromHTML ~ absolutePath:", absolutePath)

  return absolutePath
}

export default async (arrayBuffer: ArrayBuffer, msg: MessageApi) => {
  message = msg
  const book: Book = Epub(arrayBuffer)
  await book.loaded.spine
  const spine = book.spine
  const spineItems = (spine as unknown as { items: ISpineItem[] }).items

  const archive = book.archive
  const textPromises = spineItems.map((item: ISpineItem) => archive.getText(item.canonical))
  const textArr = await Promise.all(textPromises)
  const imgEles = textArr.map((item) => extractImageUrlsFromHTML(item))
  const urlPromises = imgEles.map((img) => archive.createUrl(img, { base64: false }))
  book.destroy()

  return urlPromises
}
